<template>
  <view class="home">
    <up-navbar placeholder title="搬搬货">
      <template #left>
        <view @click="handlerSign" class="sign_btn flex_c">
          <image src="@/static/images/home/sign.png" />
          {{ isSign ? '已签到' : '签到' }}
        </view>
      </template>
    </up-navbar>
    <view class="content">
      <view class="title mt24">我要用工</view>
      <view class="selectworker mt24 flex_b" @click="chooseWorker">
        <text>{{ selectWrokerForm.workType ? selectWrokerForm.workType : "请选择工种" }}</text>
        <up-icon name="arrow-right" color="#222222"></up-icon>
      </view>
      <view class="selectworker mt24 flex_b" @click="chooseTime">
        <text>{{ selectWrokerForm.workDate ? selectWrokerForm.workDate : "预约用工时间" }}</text>
        <up-icon name="arrow-right" color="#222222"></up-icon>
      </view>
      <view class="selectworker mt24 flex_b" @click="chooseAddress">
        <text>{{ selectWrokerForm.workPlace ? selectWrokerForm.workPlace : "请选择用工地点" }}</text>
        <up-icon name="arrow-right" color="#222222"></up-icon>
      </view>
      <view class="selectworker mt24 flex_b" v-if="selectWrokerForm.workPlace">
        <up-input placeholder="输入详细地址" border="none" v-model="selectWrokerForm.address"></up-input>
      </view>
      <view class="btn flex_c" @click="next">下一步</view>
      <view class="tips flex_b">
        <view class="item" @click="toPrecautions">
          <image src="@/static/images/home/home_icon_1.png" />
          <text>注意事项</text>
        </view>
        <view class="item" @click="toInsurance">
          <image src="@/static/images/home/home_icon_2.png" />
          <text>保险保障</text>
        </view>
        <view class="item" @click="toSupervise">
          <image src="@/static/images/home/home_icon_3.png" />
          <text>平台监管</text>
        </view>
      </view>
    </view>
    <view class="coupon">
      <view class="coupon_title">首次优惠</view>
      <view class="coupon_use" @click="toCoupon">去看看</view>
      <image
        src="https://www.banbanhuo.com/minio/banbanhuo/269e13b3c6983aa19b4d763c830e4e3ebf9183a7affcfe01a6f58fa828bc6756.png" />
    </view>
    <!-- 选择工种 -->
    <up-popup :show="showSelectWorker" :round="10" @close="close">
      <selectWorker :workerTypeList="workerTypeList" @selectItem="selectItem"></selectWorker>
    </up-popup>
    <!-- 选择日期和时间 -->
    <u-datetime-picker ref="datetimePickerRef" :formatter="formatter" :minDate="new Date().getTime()"
      :show="showSelectTime" v-model="datetime" mode="datetime" confirmColor="#FE6E04" @cancel="showSelectTime = false"
      @confirm="confirmSelectTime"></u-datetime-picker>
    <!-- 地区提示 -->
    <up-modal showCancelButton :show="showTips" title="提示" @confirm="confirm" @cancel="showTips = false">
      <view>平台目前正在全国范围内推广，您所在的城市暂时没有开通服务，<text style="color: #FE6E04;">请关注“搬搬货”公众号，留意推广进展</text>。</view>
    </up-modal>
  </view>
</template>

<script lang="ts" setup>
import { onReady, onShow } from '@dcloudio/uni-app';
import { ref, reactive, toRefs, computed } from 'vue';
import selectWorker from '../components/selectWorker.vue';
import { getTime, showLogin, isSameDay } from '@/utils';
import { getDictList } from '@/api/index/index';
import { getSign, createSign } from '@/api/customerPage/home'
import { useMemberStore } from '@/stores';
const memberStore = useMemberStore();
const datetimePickerRef = ref<any | null>(null);

const { isLogin, userInfo } = toRefs(memberStore)

onShow(() => {
  uni.hideTabBar()
  // 支付成功后打开首页会初始化数据 否则保留选择的内容
  const resetHomeFormFlag = uni.getStorageSync('resetHomeFormFlag')
  if (resetHomeFormFlag) {
    resetForm()
    uni.removeStorageSync('resetHomeFormFlag')
  }
  // 进入首页后判断是否登录
  if (!isLogin.value) {
    // showLogin()
  } else {
    // 获取字典表数据
    getDictListData()
    // 获取签到信息
    getSignList()
  }
})

onReady(() => {
  // 微信小程序需要用此写法
  if (datetimePickerRef.value) {
    datetimePickerRef.value.setFormatter(formatter);
  }
});

export interface SelectWorkerForm {
  workType: string
  workDate: string
  workPlace: string
  lat: number
  lng: number
  address: string
}
const selectWrokerForm = reactive<SelectWorkerForm>({
  workType: "",
  workDate: "",
  workPlace: "",
  lat: 0, // 纬度
  lng: 0, // 经度
  address: ""
})

const resetForm = () => {
  selectWrokerForm.workType = ""
  selectWrokerForm.workDate = ""
  selectWrokerForm.workPlace = ""
  selectWrokerForm.lat = 0
  selectWrokerForm.lng = 0
  selectWrokerForm.address = ""
}
// 查询字典表工种
interface Item {
  id: string
  label: string
  value: string
  dictType: string
}

const workerTypeList = ref<Item[]>([])
const getDictListData = async () => {
  const res: any = await getDictList("worker_type")
  if (res.data.length > 0) {
    workerTypeList.value = res.data
  }
}
// 选择工种
const showSelectWorker = ref(false)
const chooseWorker = () => {
  showSelectWorker.value = true
}
const close = () => {
  showSelectWorker.value = false
}
const selectItem = (item: Item) => {
  selectWrokerForm.workType = item.label
  showSelectWorker.value = false
}

// 选择时间
const showSelectTime = ref(false)
const datetime = ref("")
const formatter = (type: any, value: any) => {

  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  return value;
};

const chooseTime = () => {
  showSelectTime.value = true
}
const confirmSelectTime = (e: any) => {
  const time = getTime(e.value)
  selectWrokerForm.workDate = time
  showSelectTime.value = false
}

// 选择地址
const chooseAddress = (() => {
  uni.chooseLocation({
    type: 'gcj02',
    success: function (res) {
      selectWrokerForm.lat = res.latitude
      selectWrokerForm.lng = res.longitude
      selectWrokerForm.workPlace = res.address
      checkAddress(res.address)
    }
  })
})
// 检测详细地址是否在上海
const isShangHai = ref(false)
const showTips = ref(false)
const checkAddress = (address: string) => {
  if (address.indexOf("上海") == -1) {
    isShangHai.value = false
  } else {
    isShangHai.value = true
  }
}
// 跳转到用工详情
const next = (() => {
  if (!isLogin.value) {
    showLogin()
    return
  }
  // 判断是否上海地区
  if (!isShangHai.value) {
    showTips.value = true
  }else{
    confirm()
  }
})
const confirm = () => {
  showTips.value = false
  // 校验
  if (!selectWrokerForm.workType) {
    uni.showToast({
      title: "请选择工种",
      icon: "none"
    })
    return
  }
  if (!selectWrokerForm.workDate) {
    uni.showToast({
      title: "请选择用工时间",
      icon: "none"
    })
    return
  }
  if (!selectWrokerForm.workPlace) {
    uni.showToast({
      title: "请选择用工地点",
      icon: "none"
    })
    return
  }
  uni.hideKeyboard()
  uni.showLoading({ title: "提交中" })
  setTimeout(() => {
    uni.hideLoading()
    uni.navigateTo({
      url: "/pages/customerPage/addWorker/addWorker",
      success: function (res) {
        res.eventChannel.emit("selectWorkerForm", selectWrokerForm)
      }
    })
  }, 500)
}

/**
 * 签到
 */
// 查询签到
const isSign = computed(() => {
  let flag = false
  if (signList.value.length == 0) {
    flag = false
  } else {
    // 获取最后一次签到的时间
    const lastSignData: any = signList.value[0]
    const lastSign = lastSignData?.createTime
    const nowTime = new Date().getTime()
    // 判断是否是同一天
    const isSameDayFlag = isSameDay(lastSign, nowTime)
    flag = isSameDayFlag
  }
  return flag
})
const signDay = computed(() => {
  return signList.value.length
})
const signList = ref([])
const getSignList = async () => {
  const par = {
    userId: userInfo.value?.userId
  }
  const res: any = await getSign(par.userId)
  if (res.code == 0 && res.data?.list) {
    signList.value = res.data.list
  }
}
// 点击签到
const handlerSign = async () => {
  if (!isLogin.value) return
  if (isSign.value) {
    uni.showToast({
      title: "今天已经签到过了,请明天再来吧~",
      icon: "none"
    })
    return
  }
  const par = {
    userId: userInfo.value?.userId,
    point: 1
  }

  const res: any = await createSign(par)
  if (res.code == 0 && res.data) {
    uni.showToast({
      title: "签到成功",
      icon: "none"
    })
    getSignList()
  }
}
// 跳转到保险保障
const toInsurance = () => {
  uni.navigateTo({
    url: "/pages/public/insurance/insurance"
  })
}
// 跳转到注意事项
const toPrecautions = () => {
  uni.navigateTo({
    url: "/pages/public/precautions/precautions"
  })
}
// 跳转到平台监督
const toSupervise = () => {
  uni.navigateTo({
    url: "/pages/public/supervise/supervise"
  })
}
// 跳转到优惠券
const toCoupon = () => {
  uni.navigateTo({
    url: "/pages/other/coupon/couponList"
  })
}

</script>

<style lang="scss" scoped>
@import "./customerHome.scss";

.home {
  min-height: 100vh;
  overflow: hidden;
  background: #F8F8F8;
}
</style>